package com.example.wificon;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;

import android.widget.AdapterView.OnItemClickListener;

import android.widget.AdapterView;

import android.widget.TextView;
import android.widget.Toast;
import comm.savagelook.android.*;


public class TargetList extends Activity{
	 
	private static final String TASKS_URL = "http://10.0.2.2:3000/tasks.json";
	private SharedPreferences mPreferences;

	Button home;
	Button exit;
	Button settings;
	Button manageWiFi;
	Button getTask;
	Button create;
	TableLayout tableView;
	 
	static String[] numbers;// = new String[]; //{ 
			/*"No", "Address", "Name", "Password", "Keyword" ,"Website", "Status",
			"1", "Address 1", "Connect to 1", "123", "connect","www.website.com", "Dropdown",
			"2", "Fondovi Jilishta", "Hrizantem4o", "321", "fondo","www.website.com", "Dropdown",
			"3", "Florokompni", "leopard", "123", "kondo","www.website.com", "Dropdown",
			"212", "Ulica Sezam", "kakadu", "321", "pongo","www.website.com", "Dropdown",
			"212", "Ulica Sezam", "kakadu", "321", "pongo","www.website.com", "Dropdown",
			"212", "Ulica Sezam", "kakadu", "321", "pongo","www.website.com", "Dropdown",
			"212", "Ulica Sezam", "kakadu", "321", "pongo","www.website.com", "Dropdown",
			"212", "Ulica Sezam", "kakadu", "321", "pongo","www.website.com", "Dropdown",
			"212", "Ulica Sezam", "kakadu", "321", "pongo","www.website.com", "Dropdown",
			"212", "Ulica Sezam", "kakadu", "321", "pongo","www.website.com", "Dropdown",*/
			//};
	@Override
	
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.target_list);
		
		mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
	

		// TODO Auto-generated method stub
		 
		home = (Button) findViewById(R.id.home_button_list);
		home.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		
		exit = (Button) findViewById(R.id.exit_button);
		exit.setX(140);
		exit.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				System.exit(0);
			}
		});
		settings = (Button) findViewById(R.id.settings_button);
		settings.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				ChangeScreen("ACCOUNT_SETTINGS");
			}
		});
		manageWiFi = (Button) findViewById(R.id.manage_wifi_button);
		manageWiFi.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				ChangeScreen("MANAGE_NETWORKS");
			}
		});
		getTask = (Button) findViewById(R.id.get_task_button); // not exatly
		getTask.setX(175);
		getTask.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				ChangeScreen("GET_TASK");
			}
		});
	}
		            
		 
	    /*
		(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
				int position, long id) {
			   Toast.makeText(getApplicationContext(),
				((TextView) v).getText(), Toast.LENGTH_SHORT).show();
			}
		});
 */
	
	@Override
	public void onResume() {
	    super.onResume();

	    if (mPreferences.contains("AuthToken")) {
	        loadTasksFromAPI(TASKS_URL);
	    } else {
	        Intent intent = new Intent(TargetList.this, Home.class);
	        startActivityForResult(intent, 0);
	    }
	}

	private void generateTable()
	{
		try{
			Log.i("length2", " " + numbers.length);
			int itemNumber = numbers.length;
            TextView[] tView = new TextView[itemNumber];    
            int counter = 0;
            
            tableView = (TableLayout) findViewById(R.id.target_table);                       
            Context context = this;
            
    	    TableRow[] tableRow = new TableRow[itemNumber / 7];
            for(int j = 0;j < itemNumber / 7;j++){
           	 tableRow[j] = new TableRow(context);
                for(int i = 0;i <= 6;i++){  
               	
               	 if(j != 0 && i == 6){
               		 Spinner status = new Spinner(this);
               		 ArrayList<String> statusList =  new ArrayList<String>();
               		 statusList.add("Finished");
               		 statusList.add("Missed");
               		 statusList.add("-Status-?");
               		 ArrayAdapter<String> statusArrayAdapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, statusList);
               		 status.setAdapter(statusArrayAdapter);
               		 status.setOnItemSelectedListener(new OnItemSelectedListener() {
               			    @Override
               			    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
               			    	switch(position){
               			    	case 0 :
               			    		selectedItemView.setBackgroundColor(0xFF00FF00 );
               			    		break;
               			    	case 1 :
               			    		selectedItemView.setBackgroundColor(0xFFFF0000 );
               			    		break;
               			    		
               			    	case 2 :
               			    		selectedItemView.setBackgroundColor(0xFFFFFFFF );
               			    		break;
               			    		
               			    	default : 
               			    		selectedItemView.setBackgroundColor(0xFFFFFFFF );
                   			    	//parentView.setBackgroundColor(0xAA00FF00 );
               			    		break;
               			    	}
               			    	
               			    }
               			    @Override
               			    public void onNothingSelected(AdapterView<?> parentView) {
               			        // your code here
               			    }

               			});
               		 status.setSelection(2);
               		 tableRow[j].addView(status);
               		 counter += 1;
               	 }
               	 
               	 else{
               		 tView[i] = new TextView(this);
               		
	                     tView[i] = new TextView(context);
	
	                     tView[i].setText(numbers[counter].toString());      
	                     tView[i].setTextSize(12);
	                     counter += 1;
	                     
	                     tView[i].setTextColor(Color.rgb( 100, 200, 200));            
	                     tView[i].setGravity(0x11);
	                     if( i == 0){
               			 tView[i].setWidth(80);
               		 }
               		 else{
               			 tView[i].setWidth(160);
               			 tView[i].setHeight(60);
               		 }
	                     tableRow[j].addView(tView[i]); 
               	 }       
                }
                tableView.addView(tableRow[j]);         
            }                                           
        }catch(Exception e){
            Log.e("MainActivity", "Error in activity", e);  
            Toast.makeText(getApplicationContext(),e.getClass().getName() + " " + e.getMessage(),Toast.LENGTH_LONG).show();
        }                                
	}
			
	private void ChangeScreen(String intentName){
		Intent changeScreen;
		changeScreen = new Intent("com.example.wificon." + intentName);
		startActivity(changeScreen);
	}
	

	private void loadTasksFromAPI(String url) {
	    GetTasksTask getTasksTask = new GetTasksTask(TargetList.this);
	    getTasksTask.setMessageLoading("Loading tasks...");
        getTasksTask.execute(url + "?auth_token=" + mPreferences.getString("AuthToken", ""));

	}

	public class GetTasksTask extends UrlJsonAsyncTask {
	    public GetTasksTask(Context context) {
	        super(context);
	    }

	    @Override
	        protected void onPostExecute(JSONObject json) {
	            try {
	            	int counter = 1;
	                JSONArray jsonTasks = json.getJSONObject("data").getJSONArray("tasks");
	                int length = jsonTasks.length();
	                numbers = new String[length];
	                for (int i = 0; i < length; i++) {
	                	if( counter % 7 == 0){
	                		numbers[i] = "Status";
	                	}
	                	counter++;
	                	numbers[i] = jsonTasks.getJSONObject(i).getString("title");
	                    
	                }
	               
	            } catch (Exception e) {
	            Toast.makeText(context, e.getMessage(),
	                Toast.LENGTH_LONG).show();
	        } finally {
	            super.onPostExecute(json);
	            generateTable();
	        }
	    }
	}
}
